package com.cheetah.start.common.utils;

import cn.hutool.core.util.StrUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Feel
 * @date 2021/12/9 9:01
 * @Description:
 */
public class MyExceptionUtil {

    /**
     * 获得堆栈信息
     * 只返回项目包里的堆栈信息
     *
     * @param throwable throwable
     * @return {@link String}
     */
    public static String getStackTraceReplace(Throwable throwable, String tihuan) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        String ex = sw.toString();
        String[] split = ex.split("\n");
        List<String> stringList = new ArrayList<>();
        int length = split.length;
        if (StrUtil.isNotBlank(tihuan)) {
            for (int i = 0; i < length; i++) {
                if (split[i].contains(tihuan)) {
                    stringList.add(split[i]);
                }
            }
        }
        return stringList.toString().replace("[", "").replace("]", "");
    }


    /**
     * 获得堆栈跟踪
     *
     * @param throwable throwable
     * @return {@link String}
     */
    public static String getStackTrackStr(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        return sw.toString();
    }

    /**
     * @param throwable throwable
     * @param request   请求
     * @return {@link String}
     */
    public static String getExceptionMsg(Throwable throwable, HttpServletRequest request) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("异常:");
        String stackTrackStr = getStackTrackStr(throwable);
        stringBuilder.append(stackTrackStr);
        stringBuilder.append("\n");
        stringBuilder.append("接口信息：");
        String requestURI = request.getRequestURI();
        String param = MyServletUtil.getParam(request);
        stringBuilder.append("\n地址" + requestURI);
        stringBuilder.append("\n参数" + param);
        return stringBuilder.toString();
    }


}
